package industry;

import java.util.HashMap;

import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;

import skills.Skills;
import skills.SkillHandler;

public class Industry {
	private static final PotionEffectType SPEED = PotionEffectType.FAST_DIGGING;
	private final Player player;
	private final Block block;
	private static final HashMap<Player, Industry> buffs = new HashMap<Player, Industry>();

	public Industry(Player player, Block block) {
		this.player = player;
		this.block = block;
		applyBuff(block);
	}

	private boolean noBuff() {
		for (PotionEffect effect : player.getActivePotionEffects()) {
			if (effect.getType().equals(PotionEffectType.FAST_DIGGING)) {
				if (effect.getDuration() <= 15) {
					return false;
				}
			}
		}
		return true;
	}

	public static void applyBuff(Player player, Block block) {
		if (buffs.containsKey(player)) {
			buffs.get(player).removeBuff(player);
		}
		buffs.put(player, new Industry(player, block));
	}
	
	public static void refreshBuff(Player player, Block block) {
		if (buffs.containsKey(player)) {
			buffs.get(player).applyBuff(block);
		}
	}

	private void applyBuff(Block check) {
		if (block.equals(check)) {
			if (noBuff()) {
				int amplifier = -1;
				if (Archaeology.isDiggable(block)) {
					amplifier = SkillHandler.getSkill(player, Skills.ARCHAEOLOGY).level();
				}
				else if (Mining.isMinable(block)) {
					amplifier = SkillHandler.getSkill(player, Skills.MINING).level();
				}
				else if (Woodcutting.isLoggable(block)) {
					amplifier = SkillHandler.getSkill(player, Skills.WOODCUTTING).level();
				}
				else if (Farming.isCrop(block)) {
					amplifier = SkillHandler.getSkill(player, Skills.FARMING).level();
				}
				amplifier = amplifier / 250 - 1;
				if (amplifier > -1) {
					PotionEffect potion = new PotionEffect(SPEED, 15, amplifier);
					player.addPotionEffect(potion);
				}
			}	
		}
	}

	private void removeBuff(Player player) {
		if (buffs.containsKey(player)) {
			for (PotionEffect effect : player.getActivePotionEffects()) {
				if (effect.getType().equals(PotionEffectType.FAST_DIGGING)) {
					if (effect.getDuration() <= 15) {
						player.removePotionEffect(PotionEffectType.FAST_DIGGING);
					}
				}
			}
			buffs.remove(player);
		}
	}
}
